﻿using CloudStorageLight.Core;
using CloudStorageLight.Core.Web;
using Microsoft.SharePoint.Client;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace CloudStorageLight.SharePointWeb.Models
{
    public class BasicAuthenticateUtil //: WebBlobService
    {

        public static BlobUser GetCurrentUser()
        {
            BlobUser user;
            if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(System.Web.HttpContext.Current);

                var account = WebBlobService.GetCurrentCloudAccount();
                if (account != null && account.SpHostUrl != spContext.SPHostUrl.AbsoluteUri) throw new BlobException(BlobExceptionCode.NotAuthorization);

                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    if (clientContext != null)
                    {
                        var spUser = clientContext.Web.CurrentUser;
                        clientContext.Load(spUser, x => x.Email, x => x.Groups);
                        clientContext.ExecuteQuery();
                        var u = new AppBlobUser(new GenericPrincipal(new GenericIdentity(spUser.Email), null));

                        var ticket = new FormsAuthenticationTicket(0, spUser.Email, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, WebBlobService.GetCurrentDomain());
                        HttpCookie cookie = new HttpCookie(
                            FormsAuthentication.FormsCookieName,
                            FormsAuthentication.Encrypt(ticket));
                        System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                        System.Web.HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(spUser.Email), spUser.Groups.Select(x => x.Title).ToArray());
                    }
                }
            }
            else
            {
                var authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

                // If it exists then decrypt and setup the generic principal
                if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value))
                {
                    var ticket = FormsAuthentication.Decrypt(authCookie.Value);
                    if (WebBlobService.GetCurrentDomain() != ticket.UserData) throw new BlobException(BlobExceptionCode.NotAuthorization);
                }
            }
            user = new AppBlobUser(System.Web.HttpContext.Current.User);

            return user;

        }

        private void Init()
        {
            if (HttpContext.Current != null)
            {
                //SharePoint Webサイトログインの場合
                var ctx = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
                if (ctx != null)
                {
                    AttachedSharePointBlobAdapter.SetSpsClientContext(ctx.CreateUserClientContextForSPHost()); 
                }

                ////基本認証の場合
                //var client = (ClientContext)HttpContext.Current.Items["SpsClientContext"];
                //if (client != null)
                //{
                //    AttachedSharePointBlobAdapter.SetSpsClientContext(client);
                //}

            }
        }

        //public BlobService()
        //{
        //    Init();
        //}

        //public BlobService(CloudAccount account):base(account)
        //{
        //    Init();
        //}

    }

}